package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.UserLoginVO;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;

import java.util.Objects;

import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * @projectName: heima-leadnews
 * @package: com.heima.user.service.impl
 * @className: UserServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/11/3 11:17
 * @version: 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {

    @Override
    public UserLoginVO loginAuth(ApUser apUser) {
        if (StringUtils.isNoneBlank(apUser.getPhone(), apUser.getPassword())) {
            // 正常游客登录
            ApUser apUserByPhone = baseMapper.selectOne(
                    Wrappers.lambdaQuery(ApUser.class)
                            .eq(ApUser::getPhone, apUser.getPhone())
            );
            if (Objects.isNull(apUserByPhone)) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            // 加盐判断
            String newPas = apUser.getPassword() + apUserByPhone.getSalt();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(newPas.getBytes());
            if (!Objects.equals(md5DigestAsHex, apUserByPhone.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 封装结果并返回
            String token = AppJwtUtil.generateToken(Long.valueOf(apUserByPhone.getId()));
            apUserByPhone.setPassword(null);
            apUserByPhone.setSalt(null);
            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setUser(apUserByPhone);
            userLoginVO.setToken(token);
            return userLoginVO;
        }
        // 游客登录 --没有手机号和密码
        String token = AppJwtUtil.generateToken(0L);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
